package com.mmlc.meimei.lichengkongjian.classify;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.responsejavabean.RequestError;
import com.androidnetframe.utils.LogUtils;
import com.androidnetframe.utils.UIUtils;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.App;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.mine.DiscountCouponSelectActivity;
import com.mmlc.meimei.lichengkongjian.mine.LoginActivity;
import com.mmlc.network.filter.DefaultAddressRequestFilter;
import com.mmlc.network.filter.GetPaymentRequestFilter;
import com.mmlc.network.filter.N4NoParamsRequestFilter;
import com.mmlc.network.filter.SubmitRequestFilter;
import com.mmlc.network.responsebean.DefaultAddressResponseBean;
import com.mmlc.network.responsebean.GetPaymentResponseBean;
import com.mmlc.network.responsebean.PrepareResponseBean;
import com.mmlc.network.responsebean.SubmitResponseBean;
import com.mmlc.utils.ActivityManager;
import com.mmlc.utils.ToastUtils;
import com.mmlc.utils.ViewUtils;
import com.mmlc.widget.MyListView;

import java.util.ArrayList;
import java.util.List;


public class OrderFormActivity extends InterActivity {

    @Override
    protected int initContentView() {
        return R.layout.activity_order_form;
    }

    TextView tv_information_hint, tv_name, tv_phone, tv_address, tv_pay_content, tv_invoice_content, tv_ticket_content;
    MyListView listView;
    TextView tv_botShopCout;
    TextView tv_sendMoney;
    TextView tv_coupon;
    TextView tv_discount;
    TextView tv_finalCount;
    ToggleButton tb_scoreToaggle;
    LinearLayout rl_bottomScore;
    TextView tv_score;
    TextView tv_scoreSub;
    RelativeLayout rl_score;
    ScrollView scroll_view;
    TextView tv_send_content;
    TextView tv_dingpay,tv_dingpaynum,tv_weipay,tv_weipaynum;
    RelativeLayout rl_mode_ding,rl_mode_wei;

    @Override
    protected void initView() {
        tv_information_hint = ViewUtils.getView(activity, R.id.tv_information_hint);
        tv_name = ViewUtils.getView(activity, R.id.tv_name);
        tv_phone = ViewUtils.getView(activity, R.id.tv_phone);
        tv_address = ViewUtils.getView(activity, R.id.tv_address);
        listView = ViewUtils.getView(activity, R.id.listView);
        tv_pay_content = ViewUtils.getView(activity, R.id.tv_pay_content);
        tv_invoice_content = ViewUtils.getView(activity, R.id.tv_invoice_content);
        tv_ticket_content = ViewUtils.getView(activity, R.id.tv_ticket_content);
        tv_send_content = ViewUtils.getView(activity,R.id.tv_send_content);
        tv_information_hint.setVisibility(View.VISIBLE);

        tv_botShopCout = (TextView) findViewById(R.id.tv_botShopCout);
        tv_sendMoney = (TextView) findViewById(R.id.tv_sendMoney);
        tv_coupon = (TextView) findViewById(R.id.tv_coupon);
        tv_discount = (TextView) findViewById(R.id.tv_discount);
        tv_finalCount = (TextView) findViewById(R.id.tv_finalCount);
        tb_scoreToaggle = (ToggleButton) findViewById(R.id.tb_scoreToaggle);
        rl_bottomScore = (LinearLayout) findViewById(R.id.rl_bottomScore);
        tv_score = (TextView) findViewById(R.id.tv_score);
        tv_scoreSub = (TextView) findViewById(R.id.tv_scoreSub);
        rl_score = (RelativeLayout) findViewById(R.id.rl_score);
        scroll_view = (ScrollView) findViewById(R.id.scroll_view);


        tv_dingpay = ViewUtils.getView(activity, R.id.tv_dingpay);
        tv_dingpaynum = ViewUtils.getView(activity, R.id.tv_dingpaynum);
        tv_weipay = ViewUtils.getView(activity, R.id.tv_weipay);
        tv_weipaynum = ViewUtils.getView(activity, R.id.tv_weipaynum);
        rl_mode_ding = ViewUtils.getView(activity, R.id.rl_mode_ding);
        rl_mode_wei = ViewUtils.getView(activity, R.id.rl_mode_wei);
        processData();
    }

    String oderId;
    int orderType ;
    private void processData() {
        oderId = getIntent().getStringExtra("oderId");
        orderType = getIntent().getIntExtra("type",0);


        rl_score.setVisibility(View.GONE);
        //处理积分的开关
        tb_scoreToaggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    tb_scoreToaggle.setBackgroundResource(R.drawable.on);
                    rl_score.setVisibility(View.VISIBLE);
                    rl_score.post(new Runnable() {
                        @Override
                        public void run() {
                            scroll_view.fullScroll(ScrollView.FOCUS_DOWN);
                        }
                    });
                    initShopMoney(couponPrice);
                }else{
                    tb_scoreToaggle.setBackgroundResource(R.drawable.off);
                    rl_score.setVisibility(View.GONE);
                    rl_score.post(new Runnable() {
                        @Override
                        public void run() {
                            scroll_view.fullScroll(ScrollView.FOCUS_DOWN);
                        }
                    });
                    initShopMoney(couponPrice);
                }
            }
        });
    }

    int couponNum = 0;

    @Override
    protected void initInfo() {
        getDefaultAddress();
        getPayment();
        getCartList();
    }
    List<PrepareResponseBean.DataBean.DeliveryListBean> deliveryList = new ArrayList<>();
    PrepareResponseBean n4NoParamsResult;
    double currentPrice;
    private void getCartList() {
        final N4NoParamsRequestFilter filter = new N4NoParamsRequestFilter(activity, "prepare");
        if(orderType == 2 ){//推荐订单
            filter.requestBean.order_id = oderId;
        }
        if(orderType == 3){//直购订单
           filter.requestBean.zg_flag = 1;

        }
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<PrepareResponseBean>() {
            @Override
            public void onSuccess(PrepareResponseBean result) {
                if(result==null){
                    ToastUtils.showToast("数据解析错误");

                }
                deliveryList = result.getData().getDelivery_list();
                n4NoParamsResult = result;
                if (result == null || result.getData() == null || result.getData().getGoods_list() == null)
                    return;
                LogUtils.e(TAG, "CartList:" + result.toString());
                if (listView == null) return;
                listView.setAdapter(new OrderFormAdapter(context, result.getData().getGoods_list()));

                if (!ViewUtils.isEmpty(tv_ticket_content.getText().toString())) return;
                couponNum = result.getData().getCoupon_list().size();
                if (couponNum == 0) {
                    tv_ticket_content.setText("暂无优惠券可用");
                    ViewUtils.getView(activity, R.id.rl_mode_ticket).setClickable(false);
                } else {
                    tv_ticket_content.setText(couponNum + "张优惠券可用");
                    ViewUtils.getView(activity, R.id.rl_mode_ticket).setClickable(true);
                }

//                if(result.getData().getSuborder_info()!=null && orderType ==3){
//                    List<PrepareResponseBean.DataBean.SuborderInfoBean> info = result.getData().getSuborder_info();
//                    if(info.size()==2){
//                        tv_dingpaynum.setText("小计：¥"+info.get(0).getAmount());
//                        tv_weipaynum.setText("小计：¥"+info.get(1).getAmount());
//                        rl_mode_ding.setVisibility(View.VISIBLE);
//                        rl_mode_wei.setVisibility(View.VISIBLE);
//                    }
//                }

                //记录当前商品的价格
                currentPrice = Double.valueOf(n4NoParamsResult.getData().getOther_list().getGoods_total_price());

                //展示商品的总价格
                tv_botShopCout.setText("¥ "+n4NoParamsResult.getData().getOther_list().getGoods_total_price());

                //是否有积分
                int available_score = n4NoParamsResult.getData().getOther_list().getScore_detail().getAvailable_score();
                if(available_score == 0){
                    tv_score.setText("无可用积分");
                }else{
                    tv_score.setText(n4NoParamsResult.getData().getOther_list().getScore_detail().getContent());
                }

                //展示积分可抵用的价格
                tv_scoreSub.setText("-¥ "+n4NoParamsResult.getData().getOther_list().getScore_detail().getAvailable_score_price());

                //展示折扣
                if(!TextUtils.isEmpty(n4NoParamsResult.getData().getOther_list().getDis_price()+"")){
                    tv_discount.setText("- ¥"+n4NoParamsResult.getData().getOther_list().getDis_price());
                }
                //初始化一下，合计的价格
                initShopMoney(couponPrice);
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                ToastUtils.showToast(serverError.mess);
            }
        });

    }

    private void initShopMoney(String couponMoney) {
        double shop = n4NoParamsResult.getData().getOther_list().getGoods_total_price();

        double ship = n4NoParamsResult.getData().getOther_list().getShipping_price();

        double dis = n4NoParamsResult.getData().getOther_list().getDis_price();

        double result = 0;
        result = shop + ship;
        //是否有积分兑换
        if(tb_scoreToaggle.isChecked()){
            int scorePrice = n4NoParamsResult.getData().getOther_list().getScore_detail().getAvailable_score_price();
            double score = Double.valueOf(scorePrice);
            result = result - score ;
        }

        double coupon = 0;
        if(couponMoney != null){

            coupon = Double.parseDouble(couponMoney);
            result -= coupon;

            tv_coupon.setText("- ¥"+couponMoney);
        }else {
            tv_coupon.setText("- ¥"+0);
        }
        tv_sendMoney.setText("+ ¥"+ship);

        result -= dis;
        tv_finalCount.setText("实付: ¥"+result);

    }

    List<GetPaymentResponseBean.DataBean> payments = new ArrayList<>();

    private void getPayment() {
        GetPaymentRequestFilter filter = new GetPaymentRequestFilter(activity);
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<GetPaymentResponseBean>() {
            @Override
            public void onSuccess(GetPaymentResponseBean result) {
                if (result == null) result = new GetPaymentResponseBean();
                LogUtils.i(TAG, "getPayment:" + result.toString());
                if (result.getCode() == 0 && result.getData() != null) {
                    payments.addAll(result.getData());
                }
                if (payments.size() > 0)
                    tv_pay_content.setText(payments.get(modePay).getPay_name());
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                initInfo();
            }
        });

    }

    /**
     * 暂时使用，标识未登录，不允许选择地址和提交
     */
    boolean isLogin = true;
    DefaultAddressResponseBean.DataBean data;

    /**
     * 获取默认收货地址
     */
    private void getDefaultAddress() {
        DefaultAddressRequestFilter filter = new DefaultAddressRequestFilter(activity);
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<DefaultAddressResponseBean>() {
            @Override
            public void onSuccess(DefaultAddressResponseBean result) {
                LogUtils.i(TAG, "defaultAddress:" + result.toString());
                if (result.getData() != null)
                    data = result.getData();

                displayDefaultAddress();
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                if (failedType == 300) {
                    isLogin = false;
                    /** TODO 未登录，跳转登录 */

                    ToastUtils.showToast("请先登录账号");
                    return;
                }
            }
        });

    }

    public String sendId;

    /**
     * 展示地址
     */
    private void displayDefaultAddress() {
        sendId = data.getId();
        if (data != null && !ViewUtils.isEmpty(data.getId())) {
            tv_information_hint.setVisibility(View.GONE);

            if (!ViewUtils.isEmpty(data.getContactor()))
                tv_name.setText(data.getContactor());
            if (!ViewUtils.isEmpty(data.getPhone())) tv_phone.setText(data.getPhone());
            StringBuffer sb = new StringBuffer();
            if (!ViewUtils.isEmpty(data.getProvince_name()))
                sb.append(data.getProvince_name() + "/");
            if (!ViewUtils.isEmpty(data.getCity_name()))
                sb.append(data.getCity_name() + "/");
            if (!ViewUtils.isEmpty(data.getArea_name()))
                sb.append(data.getArea_name() + "/");
            if (!ViewUtils.isEmpty(data.getAddress())) sb.append(data.getAddress());

            tv_address.setText(sb.toString());
        } else {
            tv_information_hint.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initEvent() {
        ViewUtils.getView(activity, R.id.iv_back).setOnClickListener(this);
        ViewUtils.getView(activity, R.id.rl_information).setOnClickListener(this);
        ViewUtils.getView(activity, R.id.rl_mode_pay).setOnClickListener(this);
        ViewUtils.getView(activity, R.id.rl_mode_invoice).setOnClickListener(this);
        ViewUtils.getView(activity, R.id.rl_mode_ticket).setOnClickListener(this);
        ViewUtils.getView(activity, R.id.rl_mode_send).setOnClickListener(this);
        ViewUtils.getView(activity, R.id.tv_verify).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_information:
                if (isLogin) {
                    Intent intent = new Intent(activity, InformationSelectActivity.class);
                    intent.putExtra("from","order");
                    startActivityForResult(intent,209);
                }
                else {
                    /** TODO 跳转登录 */
                    startActivity(new Intent(activity, LoginActivity.class));
                }
                break;
            case R.id.rl_mode_pay:
                startActivityForResult(new Intent(activity, ModePaySelectActivity.class).putExtra("mode", modePay), 202);
                break;
            case R.id.rl_mode_invoice:
                startActivityForResult(new Intent(activity, ModeInvoiceSelectActivity.class).putExtra("mode", modeInvoice).putExtra("companyName", companyName), 203);
                break;
            case R.id.rl_mode_send:
                startActivityForResult(new Intent(activity, ModeSendSelectActivity.class).putExtra("mode", 0), 205);
                break;

            case R.id.rl_mode_ticket:
                Intent intent = new Intent(this, DiscountCouponSelectActivity.class);
                intent.putExtra("orderType",orderType);
                intent.putExtra("orderId",oderId);
                startActivityForResult(intent,204);
                break;
            case R.id.tv_verify://订单提交
                if (!App.user.getLoginState()) {
                    /** TODO 跳转登录 */
                    UIUtils.simpleStartActivity(LoginActivity.class);
                    return;
                }

                if (TextUtils.isEmpty(tv_name.getText().toString()) || TextUtils.isEmpty(tv_phone.getText().toString())
                    || TextUtils.isEmpty(tv_address.getText().toString()) || TextUtils.isEmpty(sendId)) {
                    ToastUtils.showToast("请完善收件人信息");
                }else {
                    orderForm();
                }
                break;
        }
    }


    /**
     * 提交订单
     */
    private void orderForm() {

        if(TextUtils.isEmpty(tv_send_content.getText())){
            ToastUtils.showToast("请选择配送方式");
            return;
        }
        SubmitRequestFilter filter = new SubmitRequestFilter(activity);
        //店铺下单
        if(orderType == 1){
            filter.requestBean.type = 1+"";
        }
        //推单
        if(orderType == 2){
            filter.requestBean.type = 2+"";
        }
        //直购
        if(orderType == 3){
            filter.requestBean.type = 3+"";

        }
        filter.requestBean.ship_code = ship_code;
        filter.requestBean.pay_code = payments.get(modePay).getPay_code();
        filter.requestBean.ship_id = sendId;
        filter.requestBean.order_id = oderId;
        if(tb_scoreToaggle.isChecked()){
            filter.requestBean.is_use_score = 1+"";
        }else{
            filter.requestBean.is_use_score = 0+"";

        }

        if (modeInvoice != -1) {
            filter.requestBean.invoice_type = modeInvoice;
            if (modeInvoice == 2)
                filter.requestBean.invoice = companyName;
        } else {
            filter.requestBean.invoice_type = 0;
        }
        if (!ViewUtils.isEmpty(couponId)) filter.requestBean.coupou_id = couponId;
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<SubmitResponseBean>() {
            @Override
            public void onSuccess(SubmitResponseBean result) {
                submitSuccess(result.getData());
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {
                LogUtils.e(TAG, "submit:" + (serverError != null ? serverError.toString() : failedType));
                ToastUtils.showToast(serverError.mess);
            }
        });
    }

    private void submitSuccess(SubmitResponseBean.DataBean dataBean) {
        Intent intent = new Intent(activity, SubmitSuccessActivity.class);
        intent.putExtra("order", dataBean)
//                .putExtra("address_id", data.getId())
                .putExtra("modeInvoice", modeInvoice == -1 ? 0 : modeInvoice)
                .putExtra("companyName", companyName)
                .putExtra("tip",dataBean.getTip());
        startActivity(intent);
        //TODO 如果提交成功
        ActivityManager.finishActivity(ProductInfoActivity.class);
        finish();
    }

    int modePay = 0, modeInvoice = -1,sendPosition = 0 ;
    String couponId, couponPrice, companyName = "",sendName,ship_code ="";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200) {
            if (requestCode == 202) {// modePay select
                if (data != null) {
                    modePay = data.getIntExtra("mode", 0);
                    if (payments != null && payments.size() > 0)
                        tv_pay_content.setText(payments.get(modePay).getPay_name());
                }
            } else if (requestCode == 203) {//modeInvoice select
                if (data != null) {
                    modeInvoice = data.getIntExtra("mode", -1);
                    companyName = "";
                    if (modeInvoice == -1) {
                        tv_invoice_content.setText("");
                    } else if (modeInvoice == 0) {
                        tv_invoice_content.setText("暂不开具发票");
                    } else if (modeInvoice == 1) {
                        tv_invoice_content.setText("开具个人发票");
                    } else if (modeInvoice == 2) {
                        companyName = data.getStringExtra("companyName");
                        tv_invoice_content.setText(companyName.length() <= 8 ? companyName : companyName.substring(0, 8) + "...");
                    }
                }
            } else if (requestCode == 204 && data != null) {
                couponId = data.getStringExtra("id");
                couponPrice = data.getStringExtra("price");
                if (!ViewUtils.isEmpty(couponId) && !ViewUtils.isEmpty(couponPrice)) {
                    tv_ticket_content.setText("-¥" + couponPrice);
                }

                //这里调用时，积分可兑换的价格，直接算为0
                initShopMoney(couponPrice);

            }else if(requestCode == 205 && data != null){
                sendPosition = data.getIntExtra("mode",0);
                sendName = deliveryList.get(sendPosition).getName();
                ship_code = deliveryList.get(sendPosition).getShip_code();
                tv_send_content.setText(sendName);

            }else if(requestCode == 209 && data!= null){
                tv_information_hint.setVisibility(View.GONE);
                if(!TextUtils.isEmpty(data.getStringExtra("id"))){
                    sendId = data.getStringExtra("id");
                }
                if(!TextUtils.isEmpty(data.getStringExtra("name"))){
                    tv_name.setText(data.getStringExtra("name"));
                }
                if(!TextUtils.isEmpty(data.getStringExtra("phone"))){
                    tv_phone.setText(data.getStringExtra("phone"));
                }
                if(!TextUtils.isEmpty(data.getStringExtra("address"))){
                    tv_address.setText(data.getStringExtra("address"));
                }

            }

        }
    }
}
